<?php
declare (strict_types = 1);

namespace app\frontend\controller;

use app\frontend\model\Article;
use app\frontend\model\ArticleComment;
use think\facade\Config;
use think\facade\Env;
use tools\es\MyElasticsearch;

class AllArticle extends Base
{
    // 首页
    public function index()
    {
        // 获取最新5条文章
        $newArticles = Article::field('id,title')
            ->where('status', 2)
            ->order('create_time', 'desc')
            ->limit(0, 10)
            ->select();

        return view('', [
            'newArticles' => $newArticles
        ]);
    }

    // 搜索列表页
    public function list()
    {
        $range = (int)input('get.range', 1);
        $keyword = input('get.keyword', '', 'strip_tags');
        $limit = input('get.limit', '2', 'strip_tags');
        $page = input('get.page', '1', 'strip_tags');

        switch ($range) {
            case 2:
                // 标题
                $query = [
                    'match' => [
                        'title' => $keyword
                    ]
                ];
                break;
            case 3:
                // 内容
                $query = [
                    'match'=> [
                        'content' => $keyword
                    ]
                ];
                break;
            case 1:
                // 全部
            default:
                // 全部
                $query = [
                    'bool' => [
                        'should' => [
                            [
                                'match' => [
                                    'title' => $keyword
                                ]
                            ],
                            [
                                'match' => [
                                    'content' => $keyword
                                ]
                            ]
                        ]
                    ]
                ];
        }


        // 从elasticsearch中搜索
        try {
            // 实例化ES工具类
            $es = new MyElasticsearch();
            $index = Env::get('es.index', 'dev_article_dev');

            // 组装搜索参数体
            $body = [
                'query' => $query,
                '_source' => [
                    'includes' => ['title', 'create_time']
                ],
                'highlight' => [
                    'pre_tags' => "<span class='highlight'>",
                    'post_tags' => "</span>",
                    'fields' => [
                        'title' => new \stdClass(),
                        'content' => new \stdClass(),
                    ]
                ],
                'from' => ($page - 1) * $limit,
                'size' => $limit
            ];

            // 进行搜索
            $res = $es->searchDoc($index, '_doc', $body);
            $articleList = [];
            foreach ($res['hits']['hits'] as $v) {
                if ($range == 2) {
                    // 如果搜索的是标题
                    $content = $v['highlight']['title'][0];
                } else {
                    // 如果搜索的是其它
                    $content = $v['highlight']['content'][0];
                }
                $articleList[] = [
                    'id' => $v['_id'],
                    'title' => $v['_source']['title'],
                    'create_time' => $v['_source']['create_time'],
                    'content' => $content
                ];
            }
        } catch (\Exception $e) {
//            return '服务器异常';
            $msg = $e->getMessage();
            die($msg);
        }

        return view('', [
            'articleList' => $articleList,
            'count' => $res['hits']['total']['value'],
            'keyword' => $keyword,
            'page' => $page
        ]);
    }

    // 文章详情
    public function detail()
    {
        $id = input('get.id');
        $article = Article::with(['articleContent', 'user'])
            ->field('id,user_id,title,create_time,update_time,up')
            ->find($id)->toArray();

        // 修改文章中图片路径
        $content = htmlspecialchars_decode($article['articleContent']['content']);
        $pattern = "/<img src=\"\/uploads\/image\//";
        $domain = Config::get('site.domain');
        $replacement = "<img src=\"{$domain}/uploads/image/";
        $content = preg_replace($pattern, $replacement, $content);

        // 获取该文章所拥有的评论
        $articleComment = ArticleComment::with(['user'])
            ->where('article_id', $id)
            ->order('create_time', 'desc')
            ->select();
        if (!$articleComment->isEmpty()) {
            $articleComment = $articleComment->toArray();
        } else {
            $articleComment = [];
        }

        return view('', [
            'id' => $id,
            'title' => $article['title'],
            'content' => $content,
            'author' => $article['author'],
            'createTime' => $article['create_time'],
            'updateTime' => $article['update_time'],
            'articleComment' => $articleComment
        ]);
    }

    // 添加评论
    public function submitComment()
    {
        $id = input('post.id');
        $comment = input('post.comment', '', 'strip_tags');
        $userInfo = session('userInfo');

        // 获取该文章的作者id
        $article = Article::field('user_id')->find($id);

        ArticleComment::create([
            'article_id' => $id,
            'content' => $comment,
            'user_id' => $userInfo['id'],
            'author_user_id' => $article->user_id,
            'create_time' => time(),
            'update_time' => time()
        ]);

        return json([
            'code' => 0,
            'msg' => '添加成功'
        ]);
    }
}
